/**
 * 初始化用户管理页面
 */
function initCustomerPage() {
    // 初始化用户表格
    initTable('customerTable', '/api/customers', [
        { field: 'id', title: 'ID' },
        { field: 'name', title: '姓名' },
        { field: 'phone', title: '电话' },
        { field: 'email', title: '邮箱' },
        {
            title: '操作',
            render: (item) => `
                <button class="btn btn-warning" onclick="editCustomer(${item.id})">编辑</button>
                <button class="btn btn-danger" onclick="deleteCustomer(${item.id})">删除</button>
            `
        }
    ]);

    // 绑定添加用户表单提交事件
    const addForm = document.getElementById('addCustomerForm');
    if (addForm) {
        addForm.addEventListener('submit', function(e) {
            e.preventDefault();
            if (validateForm(this)) {
                const formData = new FormData(this);
                const customerData = Object.fromEntries(formData.entries());

                ajaxRequest('/api/customers', 'POST', customerData,
                    () => {
                        alert('添加成功');
                        hideModal('addCustomerModal');
                        initCustomerPage();
                        this.reset();
                    },
                    (error) => {
                        alert('添加失败: ' + error.message);
                    }
                );
            }
        });
    }
}

/**
 * 编辑用户
 * @param {number} id - 用户ID
 */
function editCustomer(id) {
    ajaxRequest(`/api/customers/${id}`, 'GET', null,
        (customer) => {
            const editForm = document.getElementById('editCustomerForm');
            if (editForm) {
                for (const key in customer) {
                    const input = editForm.querySelector(`[name="${key}"]`);
                    if (input) {
                        input.value = customer[key];
                    }
                }
                showModal('editCustomerModal');
            }
        },
        (error) => {
            alert('获取用户信息失败: ' + error.message);
        }
    );
}

/**
 * 删除用户
 * @param {number} id - 用户ID
 */
function deleteCustomer(id) {
    if (confirm('确定要删除这个用户吗？')) {
        ajaxRequest(`/api/customers/${id}`, 'DELETE', null,
            () => {
                alert('删除成功');
                initCustomerPage();
            },
            (error) => {
                alert('删除失败: ' + error.message);
            }
        );
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initCustomerPage);
